/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.gui.widgets.visual;

import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import dgbgui.gui.widgets.Widget;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.util.PPaintContext;

@SuppressWarnings("serial")
public class LineWidget extends Widget {
    
    public LineWidget(PNode parent, Point2D from, Point2D to) {
        super(parent);
        
        m_line = new Line2D.Double(from,to);
        
        updateNormalisedBounds(from,to);
    }

    public boolean intersects(Rectangle2D aBounds) {
        return m_line.intersects(aBounds);
    }


    public void paint(PPaintContext aPaintContext) {
        Graphics2D g2 = aPaintContext.getGraphics(); 
        // Draw the line
        g2.setPaint(getStrokeColour());
        g2.setStroke(getStrokeStyle());
        g2.draw(m_line);
    }
    
    public void setLine(Line2D line) {
        m_line = line;
        
        // Update the bounds
        updateNormalisedBounds(line);
    }
    
    /**
     * Set the bounds using the normalised rectangle
     * @param from
     * @param to
     */
    private void updateNormalisedBounds(Point2D from, Point2D to) {
        // If the line is vertical or horizontal, it won't be drawn
        // as the bounds are zero. Therefore we add some padding to
        // ensure that it is drawn (and also to take the arrow
        // head into account)
        double x1 = Math.min(from.getX(), to.getX())-1;
        double x2 = Math.max(from.getX(), to.getX())+1;
        double y1 = Math.min(from.getY(), to.getY())-1;
        double y2 = Math.max(from.getY(), to.getY())+1;
        setBounds(x1,y1,x2-x1,y2-y1);
    }
    
    private void updateNormalisedBounds(Line2D line) {
        updateNormalisedBounds(line.getP1(),line.getP2());
    }

    
    public void setOffset(Point2D point) {
        setOffset(point.getX(), point.getY());
    }

    private Line2D m_line;

}
